<template>
  <div class="aside-all">
    <div v-if="selected.length && selected[selected.length - 1].catalogId" class="tab-title">
      <icon-svg name="iconReturn" @click.native="prev"></icon-svg>
      <el-breadcrumb separator="/" ref="factoryBread">
        <div class="elli" v-if="breadLeft < 0">...</div>
        <el-breadcrumb-item
          v-for="(item, index) in selected"
          :key="index"
          :class="{ normal: index === selected.length - 1 }"
          :style="index === 0 ? { marginLeft: breadLeft + 'px' } : null"
          @click.native="changeTab(index)"
          >{{ item.catalogNm }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <el-row>
      <el-col :span="21">
        <el-input v-model="keyword" placeholder="输入搜索关键字" @keyup.native.enter="search">
          <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="keyword.length"></i>
          <el-button slot="append" @click="search"><icon-svg name="iconSearch"></icon-svg></el-button>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-dropdown @command="handleChangeCatalog" placement="bottom" class="catalog-class-selection">
          <span>
            <el-tooltip effect="dark" content="切换体系" placement="top" :enterable="false">
              <icon-svg name="iconSystem"></icon-svg>
            </el-tooltip>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              class="catalog-class-item"
              :class="{ actived: item.catalogClassId === selectCatalogClass }"
              v-for="item in catalogClassList"
              :key="item.catalogClassId"
              :command="item"
            >
              {{ item.catalogClassNm }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <template v-if="showList.length && showList[0].assetId">
      <ul>
        <li
          v-for="item in showList"
          :key="item.assetId"
          :draggable="true"
          @dragstart="copyDrag($event, item)"
          class="drag-item tag-item"
        >
          <div class="asset-name">{{ item.assetNm }}</div>
          <div class="list-handler">
            <el-tooltip effect="dark" content="添加" placement="top" :enterable="false">
              <span class="plus" @click.prevent="$emit('addItem', item)"><i class="el-icon-plus"></i></span>
            </el-tooltip>
            <el-tooltip effect="dark" placement="top" :enterable="false">
              <span slot="content">
                口径：{{ item.bizStmt }}
                <template v-if="item.plfmDataDate">
                  <br />
                  <br />
                  数据日期: {{ item.plfmDataDate }}
                </template>
              </span>
              <icon-svg name="iconPreview" @click.native.prevent="gotoDetail(item)"></icon-svg>
            </el-tooltip>
          </div>
        </li>
      </ul>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="params.currentPageNum"
        :page-size="params.pageSize"
        :pager-count="5"
        background
        layout="total, prev, pager, next"
        small
        :total="totalSize"
      >
      </el-pagination>
    </template>
    <ul v-else-if="showList.length && showList[0].catalogId">
      <li v-for="item in showList" :key="item.catalogId" @click="handleClickCatalog(item)" class="drag-item">
        {{ item.catalogNm }} （{{ item.dataAssetCount }}）
        <i class="el-icon-arrow-right"></i>
      </li>
    </ul>
    <p v-else>{{ $parent.$parent.$parent.loading ? '' : '暂无内容' }}</p>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  data() {
    return {
      keyword: '',
      selectCatalogClass: 0,
      catalogClassList: [],
      catalogList: [],
      selected: [],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      breadLeft: 0
    }
  },
  computed: {
    showList() {
      if (!this.selected.length) return cloneDeep(this.catalogList)
      else {
        return this.selected[this.selected.length - 1]._children
      }
    }
  },
  watch: {
    selectCatalogClass() {
      this.getCatalogList()
    }
  },
  created() {
    this.getCatalogClassList()
  },
  methods: {
    handleChangeCatalog(command) {
      if (this.selectCatalogClass !== command.catalogClassId) {
        this.$confirm(`切换体系将清空配置，确定切换为【${command.catalogClassNm}？】`).then(() => {
          this.selectCatalogClass = command.catalogClassId
          this.selected = []
          this.$emit('clearConfig')
        })
      }
    },
    getBreadStyle() {
      // 面包屑样式
      this.$nextTick(() => {
        let totalWidth = 0
        let breadLeft = 0
        const bread = this.$refs.factoryBread
        if (bread) {
          let breadWidth = bread.$el.clientWidth
          for (let i = 0; i < bread.$children.length; i++) {
            totalWidth += bread.$children[i].$el.clientWidth
          }
          if (totalWidth > breadWidth) breadLeft = -(totalWidth - breadWidth + 20)
        }
        this.breadLeft = breadLeft
      })
    },
    getCatalogClassList() {
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/getAllCatalogClass'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.catalogClassList = data.data
          const basicCatalog = this.catalogClassList.find(item => item.catalogClassType === 1)
          this.selectCatalogClass = basicCatalog.catalogClassId
          this.getCatalogList()
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getCatalogList() {
      this.$emit('toggleLoading', true)
      this.$ajax({
        url: this.$ajax.setUrl(`tagFactory/catalogClassList/${this.selectCatalogClass}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data && data.data.length) {
            var catalogs = this.$utils.arrayToTree(data.data.slice(1), {
              id: 'catalogId',
              pid: 'parentCatalogId',
              mainSort: 'catalogLevel'
            })
            this.catalogList = catalogs
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.$emit('toggleLoading', false)
      })
    },
    handleClickCatalog(item) {
      if (item.tail) {
        let result = Object.assign({}, item, { _children: [] })
        this.selected.push(result)
        this.getResults(item)
      } else {
        if (!item._children || !item._children.length)
          item._children = this.findCatalog(cloneDeep(this.catalogList), item.catalogId)
        this.selected.push(item)
      }
      this.getBreadStyle()
    },
    handleCurrentChange(val) {
      this.params.currentPageNum = val
      this.getResults()
    },
    search() {
      if (!this.keyword.trim().length) {
        if (!this.selected.length || !this.selected[0].catalogId) this.selected = []
        else this.clearKeyword()
        return
      }
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.getResults()
    },
    getResults(item) {
      this.params.queryParams.listType = 1
      this.params.queryParams.assetType = 1
      this.params.queryParams.assetNm = this.keyword
      if (item && item.catalogId) this.params.queryParams.catalogId = item.catalogId
      else if (this.selected.length)
        this.params.queryParams.catalogId = this.selected[this.selected.length - 1].catalogId
      this.$emit('toggleLoading', true)
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (this.selected.length) this.selected[this.selected.length - 1]._children = data.data.records
          else {
            this.selected.push({ _children: data.data.records })
          }
          this.totalSize = data.data.totalSize
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.$emit('toggleLoading', false)
      })
    },
    gotoDetail(item) {
      this.$blank('market-tag', { params: { id: item.assetId }, newpage: true })
    },
    copyDrag(event, item) {
      this.$emit('drag', event, item)
    },
    prev() {
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.keyword = ''
      this.selected.splice(this.selected.length - 1, 1)
      this.getBreadStyle()
    },
    findCatalog(list, targetId) {
      var children = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].catalogId === targetId) {
          children = list[i]._children || []
          break
        } else {
          if (list[i]._children) {
            children = this.findCatalog(list[i]._children, targetId)
            if (children.length) break
          }
        }
      }
      return children
    },
    clearKeyword() {
      if (this.selected[this.selected.length - 1].catalogId) {
        if (this.selected[this.selected.length - 1].tail) {
          this.getResults(this.selected[this.selected.length - 1])
        } else {
          this.selected[this.selected.length - 1]._children = this.findCatalog(
            cloneDeep(this.catalogList),
            this.selected[this.selected.length - 1].catalogId
          )
        }
      } else this.selected.splice(this.selected.length - 1, 1)
    },
    clearSearch() {
      this.keyword = ''
      this.clearKeyword()
    },
    changeTab(index) {
      if (index === this.selected.length - 1) return
      this.keyword = ''
      this.selected.splice(index + 1)
      this.getBreadStyle()
    }
  }
}
</script>

<style lang="scss">
.tag-portrait {
  .aside-all {
    .el-breadcrumb {
      white-space: nowrap;
      overflow: hidden;
      position: relative;
      .el-breadcrumb__item {
        display: inline-block;
        float: none;
        &.normal .el-breadcrumb__inner {
          font-weight: normal;
        }
      }
      .el-breadcrumb__inner {
        font-size: 15px;
        font-weight: bold;
        color: #455fbc;
        &:hover {
          color: #455fbc;
        }
      }
    }
    .elli {
      width: 16px;
      height: 100%;
      content: '...';
      line-height: 10px;
      background-color: #f0f4f7;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .catalog-class-selection {
    svg {
      width: 25px;
      height: 25px;
      margin: 10px 0 0 -5px;
      color: #4d82e9;
      cursor: pointer;
    }
  }
}
</style>
